package com.lap.generator.domain.template.strategy;

import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PersistenceRepositoryImplGen implements CodeTemplate<CoreFile> {
  @Override
  public CodeType getType() {
    return CodeType.DRIVING;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();
      String repositoryImplContent =
          engine.processTemplate("adapter/driving/PersistenceRepositoryImpl.java.ftl", model);
      String repositoryImplPackName =
          PackageUtil.pack2Path(
              model.getBasePackage(),
              "adapter.driving.persistence",
              model.getModule(),
              "repository");
      String repositoryImplFile =
          FileUtil.resolverFile("java", model.getClassName(), "RepositoryImpl");

      CoreFile file =
          CoreFile.builder()
              .path(repositoryImplPackName)
              .fileName(repositoryImplFile)
              .content(repositoryImplContent)
              .build();
      
      return List.of(file);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("RepositoryImpl engine error:", e);
    }
  }
}
